package com.zoffy.zoffyapi.aop;

import com.zoffy.zoffyapi.annotion.AuthCheck;
import com.zoffy.zoffyapi.constant.UserConstant;
import com.zoffy.zoffyapi.exception.BusinessException;
import com.zoffy.zoffyapi.exception.ErrorCode;
import com.zoffy.zoffyapi.model.vo.UserVo;
import com.zoffy.zoffyapi.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class AuthInterceptor {
    @Resource
    private UserService userService;
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole= authCheck.mustRole();
        //获得当前登录用户

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        ServletRequestAttributes servletRequestAttributes=(ServletRequestAttributes)requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        UserVo userVo=userService.getCurrentUserVo(request);
        String userRole=userVo.getUserRole();
        if(userRole.equals(mustRole) || userRole.equals(UserConstant.ADMIN_ROLE)){
            return joinPoint.proceed();
        }
        throw new BusinessException(ErrorCode.FORBIDDEN_ERROR,"权限不足");
    }
}
